﻿#include "xserver_datetime.h"
#include <string.h>
#include <time.h>

#define TIME_STR_SIZE       128         // 时间字符串存储长度
#define MAX_USER_INPUT_SIZE 128
static char chat_message[MAX_USER_INPUT_SIZE];

static xnet_err_t datetime_handler (xudp_t * udp, xipaddr_t * src_ip, uint16_t src_port, xnet_packet_t * packet) {
    //udp里的local_port存的是本机端口，src_port存的是对方的端口
    //发送时间的处理函数
    xnet_packet_t * tx_packet;
    time_t rawtime;
    const struct tm * timeinfo;

    tx_packet = xnet_alloc_for_send(TIME_STR_SIZE);
    if (tx_packet == (xnet_packet_t *)0) {
        return XNET_ERR_MEM;
    }

    // 参见：http://www.cplusplus.com/reference/ctime/localtime/
    time (&rawtime);
    timeinfo = localtime (&rawtime);

    // strftime参见：http://www.cplusplus.com/reference/ctime/strftime/
    // Weekday, Month Day, Year Time-Zone
    strftime((char *)tx_packet->data, TIME_STR_SIZE, "%A, %B %d, %Y %T-%z", timeinfo);
    truncate_packet(tx_packet, (uint16_t)strlen((char *)tx_packet->data));

    return xudp_out(udp, src_ip, src_port, tx_packet);
}

xnet_err_t xserver_datetime_create(uint16_t port) {
    xnet_err_t err;

    xudp_t* udp = xudp_open(datetime_handler);
    if (udp == (xudp_t*)0) {
        return -1;
    }

    err = xudp_bind(udp, port);
    if (err < 0) {
        xudp_close(udp);
        return err;
    }
    return 0;
}

static xnet_err_t chat_handler (xudp_t * udp, xipaddr_t * src_ip, uint16_t src_port, xnet_packet_t * packet) {
    //聊天的的处理函数
    //输出包里的内容
    uint16_t message_size=(packet->size<MAX_USER_INPUT_SIZE)?packet->size:MAX_USER_INPUT_SIZE;
    memcpy(chat_message,packet->data,message_size);
    chat_message[message_size-1]='\0';
    printf("he : %s\n",chat_message);
    printf("you : ");
    scanf("%s",chat_message);

    //提示用户输入
    xnet_packet_t * tx_packet;

    tx_packet = xnet_alloc_for_send(strlen(chat_message));
    if (tx_packet == (xnet_packet_t *)0) {
        return XNET_ERR_MEM;
    }
    memcpy(tx_packet->data ,chat_message,strlen(chat_message));
    return xudp_out(udp, src_ip, src_port, tx_packet);
}

xnet_err_t xserver_udp_chat_create(uint16_t port){
    xnet_err_t err;

    xudp_t* udp = xudp_open(chat_handler);
    if (udp == (xudp_t*)0) {
        return -1;
    }

    err = xudp_bind(udp, port);
    if (err < 0) {
        xudp_close(udp);
        return err;
    }
    return 0;
};